import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierRunable implements Runnable{
    // 1、模拟最终的任务执行命令
    private boolean flag = Boolean.FALSE;
    private int count = 10;
    public CyclicBarrierRunable(boolean flag, int count) {
        this.flag = flag;
        this.count = count;
    }
    @Override
    public void run() {
        if (flag){
            System.out.println("【司令】：士兵"+count+"个，任务完成！");
        }else{
            System.out.println("【司令】：士兵"+count+"个，集合完毕！");
            flag = Boolean.TRUE;
        }
    }

    // 2、模拟士兵线程操作
    public static class SoliderRunable implements Runnable {
        private String solider;
        private CyclicBarrier cyclicBarrier;
        public SoliderRunable(String solider, CyclicBarrier cyclicBarrier) {
            this.solider = solider;
            this.cyclicBarrier = cyclicBarrier;
        }
        @Override
        public void run() {
            try {
                // 等待所有士兵到齐
                doCollection();
                cyclicBarrier.await();
                // 等待所有士兵完成任务
                doWork();
                cyclicBarrier.await();
            }catch (InterruptedException e){
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
        public void doCollection(){
            try {
                Thread.sleep(Math.abs(new Random().nextInt()%10000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("--------->>>"+solider+"集合完毕");
        }
        public void doWork(){
            try {
                Thread.sleep(Math.abs(new Random().nextInt()%10000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("--------->>>"+solider+"任务完成");
        }
    }

    // 3、线程模拟
    public static void main(String[] args) {
        final int N = 10;   // 模拟10个士兵
        boolean falg = Boolean.FALSE;
        Thread[] allSolider = new Thread[N];
        CyclicBarrier cyclicBarrier = new CyclicBarrier(N, new CyclicBarrierRunable(falg,N));
        // 设置屏障点，主要是为了执行这个方法
        System.out.println("【司令】：士兵集合！");
        for (int i = 0; i < N; i++) {
            allSolider[i] = new Thread(new SoliderRunable("士兵"+i,cyclicBarrier));
            allSolider[i].start();
        }
    }
}